package com.punai.config.sqlitedao.impl;


import cn.hutool.core.map.MapUtil;
import cn.hutool.core.util.IdUtil;
import cn.hutool.core.util.ObjectUtil;
import cn.hutool.core.util.StrUtil;
import com.punai.common.exception.ServiceException;
import com.punai.common.utils.sqlite.SqliteUtil;
import com.punai.config.sqlitedao.TemplateRepository;
import com.punai.config.sqlitedomain.Template;
import com.punai.config.sqlitesetting.SqliteSystemTemplConnection;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.domain.Page;
import org.springframework.data.domain.PageImpl;
import org.springframework.data.domain.Pageable;
import org.springframework.stereotype.Component;

import java.text.SimpleDateFormat;
import java.util.Date;
import java.util.List;
import java.util.Map;

@Component
public class TemplateRepositoryImpl implements TemplateRepository {
    private static SqliteUtil sqliteUtil;
    private static final Logger log = LoggerFactory.getLogger(TemplateRepositoryImpl.class);

    @Autowired
    private SqliteSystemTemplConnection sqliteSystemTemplConnection;

    private void initConnection() {
        sqliteUtil = sqliteSystemTemplConnection.initConnection();
    }


    @Override
    public Template findOne(String id)  {
        if(StrUtil.isBlank(id)) throw new ServiceException("模板查找失败：id不能为空");
        initConnection();
        String sql="select * from tab_config_indicator_template where id = '" + id+"'";
        Template template = sqliteUtil.selectOneRecord(Template.class, sql);
        return template;
    }

    @Override
    public List<Template> findAll()  {
        initConnection();
        String select = "SELECT " +
                "indicatorTemplate.* " +
                "FROM TAB_CONFIG_INDICATOR_TEMPLATE indicatorTemplate " +
                " WHERE 1=1 " +
                " ORDER BY indicatorTemplate.LAST_MODIFY DESC";
        List<Template> templates = sqliteUtil.selectListRecord(Template.class, select);
        return templates;
    }

  @Override
  public List<Template> findAllByType(String type) {
    initConnection();
    String select = "SELECT " +
      "indicatorTemplate.* " +
      "FROM TAB_CONFIG_INDICATOR_TEMPLATE indicatorTemplate " +
      " WHERE 1=1 " + "and type = "+ type +" " +
      " ORDER BY indicatorTemplate.LAST_MODIFY DESC";
    return sqliteUtil.selectListRecord(Template.class, select);
  }


    @Override
    public Page<Template> findPageForMap(Map<String, Object> inParams, Pageable pageable) {
        initConnection();
        int pageNumber = pageable.getPageNumber();
        int pageSize = pageable.getPageSize();
        int start = pageSize * (pageNumber-1);
        String select = "SELECT " +
                "indicatorTemplate.* " +
                "FROM TAB_CONFIG_INDICATOR_TEMPLATE indicatorTemplate " +
                " WHERE 1=1 ";
        String where = "";
        if (MapUtil.isNotEmpty(inParams)) {
            if (ObjectUtil.isNotNull(inParams.get("searchKey"))) {
                where = where + " and indicatorTemplate.SREACH_KEY LIKE '%" + inParams.get("searchKey").toString() + "%' ";
            }
            if (ObjectUtil.isNotNull(inParams.get("type"))) {
                where = where + " and indicatorTemplate.TYPE = '" + inParams.get("type").toString() + "' ";
            }
            if (ObjectUtil.isNotNull(inParams.get("name"))) {
                where = where + " and indicatorTemplate.NAME LIKE '%" + inParams.get("name").toString() + "%' ";
            }
            if (ObjectUtil.isNotNull(inParams.get("code"))) {
                where = where + " and indicatorTemplate.CODE LIKE '%" + inParams.get("code").toString() + "%' ";
            }
            if (ObjectUtil.isNotNull(inParams.get("departCode"))) {
                where = where + " and indicatorTemplate.DEPART_CODE LIKE '%" + inParams.get("departCode").toString() + "%' ";
            }
            if (ObjectUtil.isNotNull(inParams.get("id"))) {
                where = where + " and indicatorTemplate.ID = '" + inParams.get("id").toString() + "' ";
            }
        }
        String ORDER = " ORDER BY indicatorTemplate.LAST_MODIFY DESC";
        String sql = select + where + ORDER + " limit " + pageSize + " offset " + start;
        List<Template> list = sqliteUtil.selectListRecord(Template.class,sql);
        select = "SELECT count(*) as count FROM TAB_CONFIG_INDICATOR_TEMPLATE indicatorTemplate "
                + " WHERE 1=1 ";
        sql = select + where;
        Map unique = sqliteUtil.unique(sql);
        Page<Template> pageImpl = new PageImpl<>(list, pageable, Integer.parseInt(unique.get("count").toString()));
        return pageImpl;
    }

    @Override
    public void delete(String oid)  {
        if (StrUtil.isBlank(oid)) throw new ServiceException("模板删除失败：id不能为空");
        initConnection();
        String sql = "delete from tab_config_indicator_template where id = '" + oid + "'";
        sqliteUtil.execute(sql);
    }

    @Override
    public Template findMaxTemplateCode() {
        initConnection();
        String sql = "select template.* from tab_config_indicator_template template where template.code =" +
                "(select max(t1.code) as code from tab_config_indicator_template t1 )";
        Template template = sqliteUtil.selectOneRecord(Template.class, sql);
        return template;
    }

    @Override
    public Template save(Template model)  {
        initConnection();
        if(StrUtil.isNotBlank(model.getId())){
            return this.update(model);
        }
        model.setId(IdUtil.fastUUID());
        String sql="INSERT INTO tab_config_indicator_template(" +
                "ID," +
                "TYPE," +
                "NAME," +
                "CODE," +
                "DEPART_CODE," +
                "CREATE_DATE," +
                "LAST_MODIFY," +
                "SREACH_KEY," +
                "EDIT_STATE," +
                "INDIVIDUAL_ENGINEERING_TYPE," +
                "COSTS_TYPE" +
                ") " +
                "VALUES (?,?,?,?,?,?,?,?,?,?,?)";
        Object[] args = new Object[]{
                model.getId(),
                model.getType(),
                model.getName(),
                model.getCode(),
                model.getDepartCode(),
                new SimpleDateFormat("yyyy-MM-dd hh:mm:ss").format(new Date()),
                new SimpleDateFormat("yyyy-MM-dd hh:mm:ss").format(new Date()),
                model,
                1,
                model.getIndividualEngineeringType(),
                model.getCostsType(),
        };
        int rownumber = sqliteUtil.execute(sql, args);
        if (rownumber == 0) {
            throw new ServiceException("sqlite.message.addException");
        }
        return model;
    }

    @Override
    public Template update(Template model)  {
        initConnection();
        String sql = "UPDATE tab_config_indicator_template SET " +
                "TYPE=?," +
                "NAME=?," +
                "CODE=?," +
                "DEPART_CODE=?," +
                "LAST_MODIFY=?," +
                "SREACH_KEY=?," +
                "INDIVIDUAL_ENGINEERING_TYPE=?," +
                "COSTS_TYPE=? " +
                "where ID = ?";
        Object[] args = new Object[]{
                model.getType(),
                model.getName(),
                model.getCode(),
                model.getDepartCode(),
                new SimpleDateFormat("yyyy-MM-dd hh:mm:ss").format(new Date()),
                model,
                model.getIndividualEngineeringType(),
                model.getCostsType(),
                model.getId()
        };
        int rownumber = sqliteUtil.execute(sql, args);
        if (rownumber == 0) {
            throw new ServiceException("sqlite.message.updateException");
        }
        return model;
    }
}
